package com.neusoft.yiyang.customer.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.yiyang.common.entity.bed.Bed;
import com.neusoft.yiyang.common.entity.bed.BedUsage;
import com.neusoft.yiyang.common.entity.customer.Customer;
import com.neusoft.yiyang.common.entity.customer.vto.CheckInData;
import com.neusoft.yiyang.common.entity.customer.vto.CustomerWithTagBed;
import com.neusoft.yiyang.customer.client.BedUsageClient;
import com.neusoft.yiyang.customer.service.CustomerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Tag(name = "客户管理接口", description = "负责客户信息的录入、查询、更新、删除及关联操作（如护工分配、床位管理等）")
@RestController
@RequestMapping("/customers")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private BedUsageClient bedUsageClient;

    @Operation(summary = "客户入住登记", description = "新客户注册或已删除客户恢复，同时创建床位使用记录")
    @PostMapping("/register")
    public String registerCustomer(
            @Parameter(description = "客户信息（含身份证号、床位ID、入住日期等）", required = true)
            @RequestBody Customer customer) {
        Customer existingCustomer = customerService.getCustomerByIdCard(customer.getIdCard());
        if (existingCustomer != null) {
            if (existingCustomer.getIsDeleted() == 0) {
                return "该身份证号已注册";
            } else {
                customer.setIsDeleted(0);
                customer.setCustomerId(existingCustomer.getCustomerId());
                customerService.updateCustomer(customer);
                BedUsage bedUsage = new BedUsage();
                bedUsage.setCustomerId(existingCustomer.getCustomerId());
                bedUsage.setBedId(customer.getBedId());
                bedUsage.setStartDate(customer.getCheckInDate());
                bedUsage.setEndDate(customer.getContractEndDate());
                bedUsageClient.addBedUsage(bedUsage);
                return "客户信息已恢复并更新";
            }
        } else {
            customerService.registerCustomer(customer);
            BedUsage bedUsage = new BedUsage();
            bedUsage.setCustomerId(customer.getCustomerId());
            bedUsage.setBedId(customer.getBedId());
            bedUsage.setStartDate(customer.getCheckInDate());
            bedUsage.setEndDate(customer.getContractEndDate());
            bedUsageClient.addBedUsage(bedUsage);
            return "新建客户成功";
        }
    }

    @Operation(summary = "添加预期客户", description = "登记尚未正式入住的预期客户信息")
    @PostMapping("/addCustomerExpected")
    public String addCustomerExpected(
            @Parameter(description = "预期客户信息", required = true) @RequestBody Customer customer) {
        Customer existingCustomer = customerService.getCustomerByIdCard(customer.getIdCard());
        if (existingCustomer != null) {
            if (existingCustomer.getIsDeleted() == 0) {
                return "该身份证号已注册";
            } else {
                customer.setIsDeleted(0);
                customer.setCustomerId(existingCustomer.getCustomerId());
                customerService.updateCustomer(customer);
                return "客户信息已恢复并更新";
            }
        } else {
            customerService.addCustomerExpected(customer);
            return "新建客户成功";
        }
    }

    @Operation(summary = "编辑预期客户", description = "修改预期客户的信息")
    @PostMapping("/editCustomerExpected")
    public String editCustomerExpected(
            @Parameter(description = "预期客户信息（含客户ID）", required = true) @RequestBody Customer customer) {
        Customer existingCustomer = customerService.getCustomerByIdCard(customer.getIdCard());
        Customer customerById = customerService.getCustomerById(customer.getCustomerId());
        if (existingCustomer != null && !existingCustomer.getCustomerId().equals(customerById.getCustomerId())) {
            return "该身份证号已注册";
        } else {
            customerService.editCustomerExpected(customer);
            return "编辑客户成功";
        }
    }

    @Operation(summary = "删除预期客户", description = "移除预期客户记录")
    @PostMapping("/deleteCustomerExpected")
    public void deleteCustomerExpected(
            @Parameter(description = "预期客户信息（含客户ID）", required = true) @RequestBody Customer customer) {
        customerService.deleteCustomerExpected(customer.getCustomerId());
    }

    @Operation(summary = "确认客户入住", description = "将预期客户转为正式入住状态，完善入住信息")
    @PostMapping("/confirmCheckIn")
    public void confirmCheckIn(
            @Parameter(description = "入住确认数据（含客户ID、床位、合同信息等）", required = true)
            @RequestBody CheckInData checkInData) {
        customerService.confirmCheckIn(checkInData);
    }

    @Operation(summary = "根据ID查询客户", description = "获取指定客户的详细信息")
    @GetMapping("/{customerId}")
    public Customer getCustomerById(
            @Parameter(description = "客户ID", required = true) @PathVariable("customerId") Integer customerId) {
        return customerService.getCustomerById(customerId);
    }

    @Operation(summary = "查询所有正式客户", description = "获取系统中所有已正式入住的客户列表")
    @GetMapping("/all")
    public List<Customer> getAllCustomers() {
        return customerService.getAllCustomers();
    }

    @Operation(summary = "查询所有预期客户", description = "获取系统中所有尚未正式入住的预期客户列表")
    @GetMapping("/allExpected")
    public List<Customer> getAllCustomersExpected() {
        return customerService.getAllCustomersExpected();
    }

    @Operation(summary = "多条件搜索客户", description = "支持按姓名、类型、饮食标签、护工ID、身份证号筛选客户")
    @GetMapping("/search")
    public List<Customer> searchCustomers(
            @Parameter(description = "客户姓名（可选，支持模糊匹配）") @RequestParam(required = false) String customerName,
            @Parameter(description = "客户类型（可选）") @RequestParam(required = false) Integer customerType,
            @Parameter(description = "饮食标签ID（可选）") @RequestParam(required = false) Integer dietTagId,
            @Parameter(description = "护工ID（可选，查询指定护工负责的客户）") @RequestParam(required = false) Integer caretakerId,
            @Parameter(description = "身份证号（可选，精确匹配）") @RequestParam(required = false) String idCard) {
        return customerService.searchCustomers(customerName, customerType, dietTagId, caretakerId, idCard);
    }

    @Operation(summary = "分页查询客户", description = "按姓名、类型、护理等级筛选并分页返回客户列表")
    @GetMapping("/page")
    public Page<Customer> pageQuery(
            @Parameter(description = "当前页码，默认1") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数，默认10") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "客户姓名（可选，模糊匹配）") @RequestParam(required = false) String customerName,
            @Parameter(description = "客户类型（可选）") @RequestParam(required = false) Integer customerType,
            @Parameter(description = "护理等级ID（可选）") @RequestParam(required = false) Integer careLevelId
    ) {
        Page<Customer> page = new Page<>(pageNum, pageSize);
        return customerService.pageQuery(page, customerName, customerType, careLevelId);
    }

    @Operation(summary = "更新客户信息", description = "修改指定客户的基本信息（如联系方式、护理等级等）")
    @PutMapping("/{customerId}")
    public void updateCustomer(
            @Parameter(description = "客户ID", required = true) @PathVariable("customerId") Integer customerId,
            @Parameter(description = "更新后的客户信息", required = true) @RequestBody Customer customer) {
        customer.setCustomerId(customerId);
        customerService.updateCustomer(customer);
    }

    @Operation(summary = "删除客户", description = "逻辑删除客户信息（标记为删除状态，保留历史数据）")
    @DeleteMapping("/{customerId}")
    public void deleteCustomer(
            @Parameter(description = "客户ID", required = true) @PathVariable("customerId") Integer customerId) {
        customerService.deleteCustomer(customerId);
    }

    @Operation(summary = "为客户分配护工", description = "指定护工负责该客户的护理服务（传null可取消分配）")
    @PostMapping("/{customerId}/assign-caretaker")
    public void assignCaretaker(
            @Parameter(description = "客户ID", required = true) @PathVariable("customerId") Integer customerId,
            @Parameter(description = "护工ID（可选，传null取消分配）") @RequestParam(required = false) Integer caretakerId) {
        customerService.assignCaretaker(customerId, caretakerId);
    }

    @Operation(summary = "设置客户护理等级", description = "为客户指定护理等级，关联对应的护理项目")
    @PostMapping("/{customerId}/care-level/{careLevelId}")
    public void setCareLevel(
            @Parameter(description = "客户ID", required = true) @PathVariable("customerId") Integer customerId,
            @Parameter(description = "护理等级ID", required = true) @PathVariable("careLevelId") Integer careLevelId) {
        customerService.setCareLevel(customerId, careLevelId);
    }

    @Operation(summary = "获取需生成任务的客户", description = "查询已分配护工的客户列表，用于生成护理任务")
    @GetMapping("/with-caretaker")
    public List<Customer> getCustomersWithCaretaker() {
        return customerService.getCustomersWithCaretaker();
    }

    @Operation(summary = "为客户分配饮食标签", description = "指定客户的饮食禁忌或偏好标签")
    @PostMapping("/{customerId}/diet-tag")
    public void assignDietTag(
            @Parameter(description = "客户ID", required = true) @PathVariable Integer customerId,
            @Parameter(description = "饮食标签ID", required = true) @RequestParam Integer dietTagId) {
        customerService.assignDietTag(customerId, dietTagId);
    }

    @Operation(summary = "移除客户饮食标签", description = "取消客户当前的饮食标签")
    @DeleteMapping("/{customerId}/diet-tag")
    public void removeDietTag(
            @Parameter(description = "客户ID", required = true) @PathVariable Integer customerId) {
        customerService.removeDietTag(customerId);
    }

    @Operation(summary = "查询客户饮食标签", description = "获取客户当前的饮食标签ID")
    @GetMapping("/{customerId}/diet-tag")
    public Integer getDietTag(
            @Parameter(description = "客户ID", required = true) @PathVariable Integer customerId) {
        return customerService.getDietTagByCustomerId(customerId);
    }

    @Operation(summary = "根据床位列表查询客户", description = "批量查询指定床位对应的客户信息")
    @PostMapping("/getCustomerByBed")
    List<Customer> getCustomerByBed(
            @Parameter(description = "床位列表（含床位ID）", required = true) @RequestBody List<Bed> beds) {
        return customerService.getCustomerByBed(beds);
    }

    @Operation(summary = "查询已分配床位的客户", description = "获取所有已分配床位的客户列表")
    @GetMapping("/getCustomerHasBed")
    List<Customer> getCustomerHasBed() {
        return customerService.getCustomerHasBed();
    }

    @Operation(summary = "为客户更换床位", description = "更新客户的床位信息，同步调整床位使用记录")
    @GetMapping("/changeBed")
    void changeBed(
            @Parameter(description = "客户ID", required = true) @RequestParam Integer customerId,
            @Parameter(description = "新床位ID", required = true) @RequestParam Integer bedId) {
        customerService.changeBed(customerId, bedId);
    }

    @Operation(summary = "查询护工负责的客户（含床位信息）", description = "获取指定护工负责的客户及关联床位信息")
    @GetMapping("/getCustomerWithTagBedByUserId")
    List<CustomerWithTagBed> getCustomerByUserId(
            @Parameter(description = "护工ID（可选，不传则查询所有）") @RequestParam(required = false) Integer userId) {
        return customerService.getCustomerByUserId(userId);
    }

    @Operation(summary = "查询护工管理的客户列表", description = "按护工ID获取其负责的客户信息（含基本信息）")
    @GetMapping("/getByCaretakerId/{caretakerId}")
    public List<Map<String, Object>> getCustomersByCaretakerId(
            @Parameter(description = "护工ID", required = true) @PathVariable Integer caretakerId) {
        return customerService.getCustomersByCaretakerId(caretakerId);
    }

    @Operation(summary = "查询所有老人客户", description = "获取系统中所有类型为老人的客户列表")
    @GetMapping("selectAll")
    public List<Customer> selectAllCustomer() {
        return customerService.selectAllCustomer();
    }

    @Operation(summary = "查询床位使用状态统计", description = "返回总床数、空床数、预约缴费/未缴费老人数")
    @GetMapping("getBedFreeStatus")
    public Map<String, Integer> getBedFreeStatus() {
        return customerService.getBedFreeStatus();
    }
}